package cn.jetpiece.cloud.system.dp.app.modular.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.jetpiece.cloud.core.page.PageFactory;
import cn.jetpiece.cloud.core.query.QueryGenerator;
import cn.jetpiece.cloud.core.util.HttpContext;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import cn.jetpiece.cloud.starter.app.modular.base.controller.BaseController;
import cn.jetpiece.cloud.system.dp.api.biz.DpTScopeDataApi;
import cn.jetpiece.cloud.system.dp.api.biz.model.params.CreateDpTScopeDataParam;
import cn.jetpiece.cloud.system.dp.api.biz.model.params.UpdateDpTScopeDataParam;
import cn.jetpiece.cloud.system.dp.api.biz.model.query.DpTScopeDataQuery;
import cn.jetpiece.cloud.system.dp.api.biz.model.result.DpTApiResult;
import cn.jetpiece.cloud.system.dp.api.biz.model.result.DpTProjectResult;
import cn.jetpiece.cloud.system.dp.api.biz.model.result.DpTScopeDataResult;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTApi;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTProject;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTScopeData;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTApiService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTProjectService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTScopeDataService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.wrapper.DpTApiWrapper;
import cn.jetpiece.cloud.system.dp.app.modular.biz.wrapper.DpTProjectWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * dp_t_scope_data
 *
 * @author jetpiece
 * @since 2023-05-18
 */
@Slf4j
@RestController
public class DpTScopeDataController extends BaseController<DpTScopeData, IDpTScopeDataService> implements DpTScopeDataApi {

	@Autowired
	private IDpTScopeDataService dpTScopeDataService;

	@Autowired
	private IDpTProjectService dpTProjectService;

	@Autowired
	private IDpTApiService dpTApiService;

	@Override
	public Result<String> add(CreateDpTScopeDataParam param) {
		try {
			if (dpTScopeDataService.add(param)) {
				return Result.OK("添加成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Result.error("添加失败");
	}

	@Override
	public Result<String> update(UpdateDpTScopeDataParam param) {
		try {
			DpTScopeData oldBean = dpTScopeDataService.getById(param.getDataId());
			if (oldBean == null) {
				return Result.error("数据未找到!");
			}
			DpTScopeData dpTScopeData = BeanUtil.toBean(param, DpTScopeData.class);
			if (dpTScopeDataService.updateById(dpTScopeData)) {
				return Result.OK("编辑成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Result.error("编辑失败");
	}

	@Override
	public Result<String> delete(String appKey,Long projectId) {
		try {
			LambdaUpdateWrapper<DpTScopeData> updateWrapper = new LambdaUpdateWrapper();
			updateWrapper.eq(DpTScopeData::getAppKey,appKey);
			updateWrapper.setSql("project_value = replace(project_value,'"+projectId+",','')");
			if (dpTScopeDataService.update(updateWrapper)) {
				return Result.OK("删除成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return Result.error("删除失败");
	}

	@Override
	public Result<String> deleteBatch(String ids) {
		try {
			List<Integer> idList = Convert.toList(Integer.class, ids.split(","));
			if (dpTScopeDataService.removeByIds(idList)) {
				return Result.OK("批量删除成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return Result.error("批量删除失败");
	}

	@Override
	public Result<DpTScopeDataResult> get(Long id) {
		try {
			DpTScopeData dpTScopeData = dpTScopeDataService.getById(id);
			if (dpTScopeData == null) {
				return Result.error("数据未找到!");
			}
			return Result.OK(BeanUtil.toBean(dpTScopeData, DpTScopeDataResult.class));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return Result.error("获取数据失败！");
	}

	@Override
	public Result<PageResult<DpTProjectResult>> page(@Valid DpTScopeDataQuery query) {
		if(StringUtils.isBlank(query.getAppKey())){
			return defaultPageResult();
		}
		DpTScopeData dpTScopeData = BeanUtil.toBean(query, DpTScopeData.class);
		QueryWrapper<DpTScopeData> scopeQueryWrapper = QueryGenerator.initQueryWrapper(dpTScopeData, HttpContext.getRequestParameters());
		List<DpTScopeData> scopeDataList = this.dpTScopeDataService.list(scopeQueryWrapper);
		if(CollUtil.isEmpty(scopeDataList)){
			return defaultPageResult();
		}
		String projectValue = scopeDataList.get(0).getProjectValue();
		if(StringUtils.isBlank(projectValue)){
			return defaultPageResult();
		}
		LambdaQueryWrapper<DpTProject> queryWrapper = new LambdaQueryWrapper();;
		queryWrapper.in(DpTProject::getProjectId, Arrays.asList(projectValue.split(",")));
		queryWrapper.like(StringUtils.isNoneBlank(query.getProjectName()),DpTProject::getProjectName,query.getProjectName());
		queryWrapper.like(ObjectUtil.isNotNull(query.getSourceId()),DpTProject::getSourceId,query.getSourceId());
		Page<DpTProject> page = PageFactory.defaultPage();
		IPage<DpTProject> pageList = dpTProjectService.page(page, queryWrapper);
		return Result.OK(new DpTProjectWrapper(pageList).setWrapper(true).wrapPageResult());
	}

	@Override
	public Result<PageResult<DpTApiResult>> pageApi(@Valid DpTScopeDataQuery query) {
		if(StringUtils.isBlank(query.getAppKey())){
			return defaultApiPageResult();
		}
		DpTScopeData scopeData = this.dpTScopeDataService.getByAppKey(query.getAppKey());
		if(ObjectUtil.isEmpty(scopeData)){
			return defaultApiPageResult();
		}
		String apiValue = scopeData.getApiValue();
		if(StringUtils.isBlank(apiValue)){
			return defaultApiPageResult();
		}
		LambdaQueryWrapper<DpTApi> queryWrapper = new LambdaQueryWrapper();;
		queryWrapper.in(DpTApi::getId, Arrays.asList(apiValue.split(",")));
		queryWrapper.like(StringUtils.isNoneBlank(query.getApiName()),DpTApi::getName,query.getApiName());
		Page<DpTApi> page = PageFactory.defaultPage();
		IPage<DpTApi> pageList = dpTApiService.page(page, queryWrapper);
		return Result.OK(new DpTApiWrapper(pageList).setWrapper(true).wrapPageResult());
	}

	@Override
	public Result<String> addApi(@Valid CreateDpTScopeDataParam param) {
		try {
			if (dpTScopeDataService.addApi(param)) {
				return Result.OK("添加成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Result.error("添加失败");
	}

	@Override
	public Result<String> deleteApi(String appKey, Long apiId) {
		try {
			LambdaUpdateWrapper<DpTScopeData> updateWrapper = new LambdaUpdateWrapper();
			updateWrapper.eq(DpTScopeData::getAppKey,appKey);
			updateWrapper.setSql("api_value = replace(api_value,'"+apiId+",','')");
			if (dpTScopeDataService.update(updateWrapper)) {
				return Result.OK("删除成功!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return Result.error("删除失败");
	}

	private Result<PageResult<DpTProjectResult>> defaultPageResult() {
		return Result.OK(new DpTProjectWrapper(PageFactory.defaultPage()).setWrapper(true).wrapPageResult());
	}

	private Result<PageResult<DpTApiResult>> defaultApiPageResult() {
		return Result.OK(new DpTApiWrapper(PageFactory.defaultPage()).setWrapper(true).wrapPageResult());
	}
}
